//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BookViewController.h"
#import "BoxTableViewController.h"
#import "SmsViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
#import<QuartzCore/QuartzCore.h>
@interface BookViewController ()
@property (nonatomic, strong) PMCalendarController *pmCC;

@end

@implementation BookViewController
@synthesize mainView;
@synthesize tbTime;
@synthesize tbDate;
@synthesize tbDiningNumber;
@synthesize tbMemo;
@synthesize btBook;
@synthesize lbTitle;
@synthesize tbBoxType;
@synthesize pmCC;
@synthesize boxIds;
@synthesize merchantName;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self initDefault];
    [self getTables];
    
}
- (void)initDefault{
    tbDiningNumber.delegate = self;
    tbMemo.delegate = self;
    NSDate *curDate = [NSDate date];//获取当前日期
    tbDate.text = [NSString stringWithFormat:@"就餐日期：%@", [curDate dateStringWithFormat:@"yyyy-MM-dd"]];
    NSString *d = [curDate dateStringWithFormat:@"yyyy-MM-dd"];
    if (![diningDate isEqualToString:d]) {
        diningDate = [d copy];
    }
    lbTitle.text = merchantName;
    diningTime = 1;
    tbTime.text = [NSString stringWithFormat:@"就餐时段： %@",@"上午6:00-11:00"];
    boxType = 0;
    
    mainView.layer.cornerRadius=5;
    mainView.layer.borderWidth=1;
    mainView.layer.borderColor=[UIColor lightGrayColor].CGColor;
}
- (void) getTables{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxType];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    [request setDelegate: self];
    [request startAsynchronous];

}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayBoxType = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxTypeID",@"不限",@"boxTypeDesc",nil];
    [arrayBoxType insertObject: dict atIndex:0];

//    NSLog(@"%@", arrayBoxType);
    //评论页面
    NSURL * url = [NSURL URLWithString:url_diningTime] ;
    request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    jsonStr = [request responseString];
    dic = [jsonStr JSONValue];
    arrayDiningTime = [dic valueForKey:@"data"];
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void)viewDidUnload
{
    [self setTbBoxType:nil];
    [self setTbTime:nil];
    [self setTbDate:nil];
    [self setMainView:nil];
    [self setTbDiningNumber:nil];
    [self setTbMemo:nil];
    [self setBtBook:nil];
    [self setLbTitle:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"包厢搜索";
    }
    return self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    //    if (theTextField == self.textField) {
    [theTextField resignFirstResponder];
    //    }
    return YES;
}
- (IBAction)showBoxType:(id)sender {
    BoxTableViewController  *view = [[BoxTableViewController alloc] initWithNibName:@"BoxTableViewController" bundle:nil];
    view.merchantId = _merchantId;
    view.diningDate = diningDate;
//    NSLog(@"%@",self.boxIds);
    view.diningTime = diningTime;
    view.delegate = self;
    view.selectedIds = self.boxIds;
    view.hidesBottomBarWhenPushed=YES;
	[self.navigationController pushViewController:view animated:YES];
	[view release];
}
- (void)dealloc {
    [tbBoxType release];
    [tbTime release];
    [tbDate release];
    [mainView release];
    [tbDiningNumber release];
    [tbMemo release];
    [btBook release];
    [lbTitle release];
    [super dealloc];
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex
{
    switch (selectIndex) {
        case 4:{
            tbTime.text = [NSString stringWithFormat:@"就餐时段： %@",[[arrayDiningTime objectAtIndex:anIndex] objectForKey:@"timeDesc"]];
            diningTime= [[[arrayDiningTime objectAtIndex:anIndex] objectForKey:@"timeID"] intValue];
            break;}
        case 5:{
            tbBoxType.text = [NSString stringWithFormat:@"包厢类型： %@",[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeDesc"]];
            boxType= [[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeID"] intValue];
            break;}
        
        default:
            break;
    }
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
}


- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showDiningTime:(id)sender {
    selectIndex = 4;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择就餐时段..." options:arrayDiningTime];
    lplv.name = @"timeDesc";
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
    [lplv release];
}


- (IBAction)showCanlendar:(id)sender {
    self.pmCC = [[PMCalendarController alloc] init];
    pmCC.delegate = self;
    pmCC.mondayFirstDayOfWeek = YES;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyy-MM-dd"];
    pmCC.period = [PMPeriod oneDayPeriodWithDate:[formatter dateFromString:diningDate]];
    
    [pmCC presentCalendarFromView:sender
         permittedArrowDirections:PMCalendarArrowDirectionAny
                         animated:YES];
    pmCC.allowsPeriodSelection = YES;
    /*[pmCC presentCalendarFromRect:[sender frame]
     inView:[sender superview]
     permittedArrowDirections:PMCalendarArrowDirectionAny
     animated:YES];*/
    [self calendarController:pmCC didChangePeriod:pmCC.period];

}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    tbDate.text = [NSString stringWithFormat:@"就餐日期：%@", [newPeriod.endDate dateStringWithFormat:@"yyyy-MM-dd"]];
    NSString *d = [newPeriod.endDate dateStringWithFormat:@"yyyy-MM-dd"];
    if (![diningDate isEqualToString:d]) {
        diningDate = [d copy];
        [[calendarController view ] removeFromSuperview];
    }
}
//提交订单
- (IBAction)doBook:(id)sender {
    
    NSURL *url = [NSURL URLWithString:url_order];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    int memberId = [[Config Instance] getMemberId];
    [request setPostValue:[NSString stringWithFormat:@"%d",memberId] forKey:@"memberID"];
    [request setPostValue:[[Config Instance] getPassword] forKey:@"password"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    [request setPostValue:[NSString stringWithFormat:@"%d",1] forKey:@"cityID"];
    [request setPostValue: tbDiningNumber.text forKey:@"diningNumber"];
    [request setPostValue: diningDate forKey:@"diningDate"];
    [request setPostValue:[NSString stringWithFormat:@"%d",diningTime] forKey:@"diningTime"];
    [request setPostValue: tbMemo.text forKey:@"memo"];
    [request setPostValue: @"4" forKey:@"orderFrom"];
    [request setPostValue: boxIds forKey:@"boxIDs"];

    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSLog(@"%@",dic);
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        NSDictionary * data = [dic valueForKey:@"data"];
        SmsViewController  *view = [[SmsViewController alloc] initWithNibName:@"SmsViewController" bundle:nil];
        view.orderNo=[data valueForKey:@"orderNO"];
        view.content = [data valueForKey:@"inviteSMS"];
        btBook.enabled=NO;
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        [view release];
    }else{
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:[dic valueForKey:@"log"] 
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
     
//    SmsViewController  *view = [[SmsViewController alloc] initWithNibName:@"SmsViewController" bundle:nil];
//    view.hidesBottomBarWhenPushed=YES;
//    [self.navigationController pushViewController:view animated:YES];
//    [view release];
}
//实现传参协议的方法
#pragma mark UIViewPassValueDelegate mothod
- (void)passBoxNames:(NSString *)boxNames withIds:(NSString *) Ids
{
    self.tbBoxType.text = [NSString stringWithFormat:@"选择包厢：%@",boxNames];
    self.boxIds = Ids;
    
//    NSLog(@"%@",boxIds);

}

@end
